\def\codefont{
  \fontspec{Courier New}
  \fontsize{9pt}{11pt}\selectfont}

\newenvironment{code}
{\begin{center}
    \begin{tikzpicture}
      \node [fill=codebgcolor,rounded corners=5pt]
      \bgroup
      \bgroup\codefont
      \begin{tabular}{l}}
      {\end{tabular}
      \egroup
      \egroup;
    \end{tikzpicture}
  \end{center}}

\chapter{Implementation details}
The implementation relies on the assumption of point to point communication
between the transmitter and the receiver. It is based on the ARL UNET-2 stack.

\section{Software Architecture}
Transport ARQ protocols are implemented using FAPI Agent framework and Java
programming language. The Figure\ref{compdiag} explains the architecture
details.
\begin{figure}[h!]
   \includegraphics[scale=0.4]{./img/design.png}
      \caption{Transport ARQ Agent and main components} 
      \label{compdiag}
\end{figure}

TransportARQ agent is implemented by extending the FAPIAgent class. Agent
performs the requested operations by command handler or FAPI message. It is
also responsible for handling incoming parameter(get/set) requests. To manage
the segmentation and reassembly of user data it delegates this operation, to the
Segmentation and Reassembly manager(s). These managers convert user data/file to
blocks or packets and vice versa. In following subsections the explanation for
implementation details is provided in the form of packet structure and class
diagrams.
\subsection{Main Components}
Main software components of implemented agent are shown in Figure
\ref{compdiag}. All components handle the execution of appropriate events
based on the chosen protocol type. The functionalities are reused where ever
possible
 \subsubsection*{Segmentation Manager} Segmentation manager is used by
the transmitter to packetize the data/file. 
It splits the total data into smaller chunks with the help of packet factory. 
These small chunks are Transport layer Protocol Data Units (PDU) and the size
 of this PDU is calculated based on physical
 layer packet size and the overheads associated with the link layer and
 transport layer. Transport layer packet contains
 packet header and these PDU as data. The main tasks of the Segmentation Manager
 are as follows:
 \begin{itemize}
   \item Segmentation of data/file
   \item Transmission of Metadata info packet
   \item Reception of Metadata infoACK packet
   \item Transmission of a block of Data packets
   \item Reception of block ACK packets
\end{itemize}
 
  \subsubsection*{Packet Factory}
  Packet factory encapsulates the process of fetching and managing
  ACK/unACK packets. It converts all chunks of data into transport packet.
  It assigns a unique packet id and the destination Medium Acess Control (MAC)
  address to all the transport packets.
  It also helps in encapsulating multiple packets into a block of packets with a
  blockId and a blockPacketId.
  
  \subsubsection*{Reassembly Manager} 
  In ARQ based protocols retransmissions at the transmitter will lead to
  reception of packets in un-ordered manner(at the receiver). Therefore
  Reassembly Manager takes care to reorder and recover the orignal file
  back at the receiver's end. It is also responsible for the formation and
  transmission of ACK packets back to the transmittor. Main tasks can be
  classified as:
  \begin{itemize}
   \item Re-assembly of data/file
   \item Reception of Metadata info packet
   \item Transmission of Metadata infoACK packet
   \item Reception of a block of Data packets
   \item Transmission of block ACK packets
\end{itemize}
   
 \subsubsection*{Rx Helper}
 Rx helper is implemented to support the Reassembly Manager for handling
 incoming data packets and forming the ACK packet. The ACK packet will contain
 appropriate information if some corrupted data packets are
 received or if some data packets are missed.
 It also provides confirmation about completion of transmission.
 
  \subsubsection*{Tx and Rx timers}
  Tx timers are used to trigger events for scheduling next
  packet or block transmission. It handles the calculation of next
  transmission time based on a chosen protocol(ARQ, JARQ).
  \\
  Rx timers are used to identify if some packets are missed at the
  receiver, based on the delay between the incoming packets. It also informs
  the Reassembly Manager to transmitg the ACK packet on reception of all packets
  or when the timer expires.
  \subsubsection*{Transport Packet} 
  Transport Packet is a representation component for transport layer packet. It
  also provides encoding and decoding of transport packet to/from byte array.
  For a chosen protocol packet encoding and decoding is handled appropriately.
  The following section explains in detail the packet structure of different
  protocols.
  \subsubsection*{Parameter calculator}
  Transmission throughput depends on various factors such as Bit Error
  Rate(BER), packet detection probability and parameters such as packet size,
  block size etc.
  In \cite{jugglenotjuggle} algorithms to estimate these parameters have been
  suggested. Parameter calculator provides an implementation of these
  algorithms. Detailed analysis of parameter calculations is described in
  later sections.
  
  \subsubsection*{Block} 
  Block is a representation object to contain a set
  of packets depending upon block size. It also assigns a blockID and blockpacketID to packets.
\subsubsection*{Rateless Codec}
In \cite{arvindproject} the implementation of encoding and decoding mechanism
using rateless codes is described.
This has been integrated with J-ARQ.
\subsection{Transport Packet Structure}
\begin{figure}[h!]
   \includegraphics[scale=0.4]{./img/packets.png}
      \caption{Transport Packet Structure} 
\end{figure}
Every Transport packet contains a few header bytes and data bytes.The header
contains information such as packetId, messageType etc. All control messages are sent
using a configured control scheme (which is generally more robust) and the data
packets are transmitted using a configured data scheme. Currently the
different message types are categorized as follows
\begin{itemize}
  \item MESSAGETYPE\_INFO : (Control Scheme) A packet type containing metadata
  information; about the start of transmission.
  \item MESSAGETYPE\_INFOACK : (Control Scheme)A packet type containing ACK for
  INFO message.
  \item MESSAGETYPE\_DATA : (Data Scheme)A packet type containing user data
  \item MESSAGETYPE\_ACK : (Control Scheme)A block ACK for multiple Data packets
  \item MESSAGETYPE\_RXCOMPLETE : (Control Scheme)A ACK for indicating the
  completion of transfer; with ACK of all packets.
\end{itemize}

\subsection{Class Diagrams}
Based on the main components highlighted in the Software Architecture, the class
diagrams on the actual implementation are in Figure~\ref{class_diag}. 
 \begin{figure}[h!]
   \includegraphics[scale=0.4]{./img/classdiag.png}
      \caption{Transport ARQ agent (Class diagrams)}
      \label{class_diag} 
\end{figure}

\section{AT Commands}
Several AT commands\cite{atcommands} have been implemented for transport layer,
protocol configurations and performing various operations. AT commands are a
method to access the modem in a human-readable form.
\begin{itemize}
  \item \nolinkurl{AT~TP?} - list parameter names
 
 
  This command lists all the configuration parameters which can be used for
  switching between protocols and also for configuration by users. Following
  are the parameters mainly used:
  \begin{itemize}
    \item ENABLE (1): To enable(1) and disable(0) the transport layer
    \item ARQ\_TYPE (3): Specifies the type of transport layer ARQ protocol
    (explained in later part of this section) being used for transmission. It
    can have 4 values:
    \begin{itemize}
      \item Fixed Block ARQ(0)
      \item Variable Block ARQ(2)
      \item Juggling-like ARQ(1)
      \item Juggling-like ARQ with Rateless codes(3)
\end{itemize}
    \item SCHEME\_DATA (6): Physical layer scheme(a set of specific FEC and
    modulation techniques) for data packets transmissions.
    \item SCHEME\_DATA\_TRIG (5):Physical layer scheme(a set of specific FEC and
    modulation techniques) for data packets transmissions with time specified.
    \item SCHEME\_CONTROL (7): Physical layer scheme for control packet
    transmissions (generally more robust than data)
    \item MAXPKTDURATION (2):Specified maximum packet duration to limit it
    within hardware supported duration    
    \item RATELESS\_CODING\_TYPE (11):Various rateless code schemes can be
    used for encoding and decoding with J-ARQ. Three types of rateless code
    schemes being used:
    \begin{itemize}
      \item Rateless with KentMap(0)
      \item Luby Transform codes(1)
      \item Random Linear Fountain codes(2)
\end{itemize} 
    \item PROTOCOL (0):The protocol field is used while communicating with the
    Link layer. It helps different messages to avoid interference with each
    other.

\end{itemize}
  
\item \nolinkurl{AT~TP.param=value} - set parameter

Parameters explained above can be set with AT command interface (e.g.
AT~TP.ARQ\_TYPE=2 or AT~TP.3=2)
\item \nolinkurl{AT~TP.param?} - get parameter

Parameters values can be obtained with AT command interface (e.g.
AT~TP.ARQ\_TYPE? or AT~TP.3?)
\item \nolinkurl{AT~TTX.PKT=src,dest,len} - Transmit packet

Command to transmit a packet/data in a point to point mode. Source and
destination addresses are provided in src,dest parameters. The len parameter
specifies the number of bytes that are to be sent accros.For example:

AT~ttx.pkt=1,2,6\\
112233445566

\item \nolinkurl{AT~TTX.TESTPKT=src,dest[,len]} - transmit a test packet

Test command to send random data of specified length.
\item \nolinkurl{AT~TTX.FILE=src,dest, filepath} - transmit a file

Command to transfer a particular file, specified with its the path reliably from
the source to destination modem. The following execution will transfer a file
test.dat from source(1) to destination(2).

AT~ttx.file=1,2 \\
$\backslash home\backslash modem\backslash etc\backslash test.dat$
\item \nolinkurl{AT~TTX.REMOTE=src,dest} - Execute any AT command remotely at
a destination

Executes any specified AT command at a destination modem. This is useful in
scenarios when a modem is not accessible by a AT command interface but
they are connected and are in range of underwater networks.
\item \nolinkurl{~TRX.DATA=src,dst,len,pktnumber} - received transport layer
DATA packet \\Notification for Data packet received 
\item \nolinkurl{~TRX.ACK=src,dst,len} - received transport layer ACK packet
\\Notification for ACK packet received
\item  \nolinkurl{~TRX.TTX.COMPLETE=src,dst,len} - transmission completed
\\Notification of Tx completion.
\end{itemize}



 


\section{Timing constraints}
All protocols here are implemented as Block based ARQ protocol. ARQ protocol
require retransmissions if packet(s) are lost during transmission. So the
identification of missing packets and retransmission of selective packet(s)
requires some timing constraints to be specified. In
underwater communication the propagation delays are long but finite it is
possible to predict the reception time of any packet which is transmitted.
Based on these calculated prediction times, few timers have been implemented to
track the missing data packets and ACK packets. The following sub sections
explain these timing constraints in detail.\\
All the protocols perform an initial handshake to exchange
the metadata information.
For ease of understanding handshake messages are not shown in following timing
diagrams.
\subsection{Fixed Block ARQ}
Fixed block ARQ protocol can be used in cases where reliable transfer of a
virtually infinite data stream is required. The number of packets in a block
(i.e. block size) is fixed and at the end of the data stream when no more data
packets are left to be transmitted; extra data packets are added to complete the packets in block. 
The Figure~\ref{farq} explains a scenario where the data contains 10 packets and
the block size is 5.Packets are represented as thin arrows with the direction
pointing towards receiver.
\\Here transmitter and receiver maintain timers for retransmissions and sending
ACK. After finishing transmission of a block; the transmitter maintains a timer
for sending the next block. The transmission of the next block is
scheduled based on if either the timer expires or ACK packet is received (which
ever is earlier).
The receiver maintains a timer for the next expected reception of a packet.ACK
packet is transmitted when all the packets of a block are received or timer
expires (which ever is earlier)
 \begin{figure}[h!]
\centering
   \includegraphics[scale=0.5]{./img/fixedarq.jpg}
   \caption{Fixed Block ARQ protocol}
   \label{farq} 
\end{figure}

\subsection{Variable Block ARQ}
Variable block ARQ behaves same as the fixed block ARQ does but with a variable
block size. For the similar scenario explained in fixed block ARQ, the block
size gets changed dynamically based on the number of packets remaining. In
the Figure\ref{varq} it can be seen clearly that for the 3rd block, block size
gets reduced from 5 to 2 (as there are only 2 packets remaining). Variable block reduces the transmission 
of unnecessary padded empty packets, but on the
otherhand it needs the varying blocksize information to be embedded in packet
header. This increases the size of a packet header.
\begin{figure}[h!]
\centering
   \includegraphics[scale=0.5]{./img/variablearq.jpg}
   \caption{Variable Block ARQ protocol} 
   \label{varq}
\end{figure}

\subsection{Fixed Block Juggling-like ARQ}
Juggling concept was introduced in\cite{arqunderwater}. The concept explains a
protocol to have better channel utilization when the propagation delays is high.
It describes juggling of data packets and ACK packets in opposite directions.
Juggling protocol requires more rigid timing constraints as it should be able to transmit
blocks with a time gap which is sufficient for receiving an ACK packet and
switch from TX half duplex mode to RX half duplex mode.
The following Figure\ref{jarq} gives a basic juggling ARQ with block size=5. For
simplicity consider only 12 packets to be transmitted. 
As shown in the figure the first two blocks (containing 10 packets)are
transmitted. The 9$^{th}$ packet is lost due to error and needs
retransmitted after getting the negative ACK for it.
 \begin{figure}[h!]
\centering
   \includegraphics[scale=0.5]{./img/jarq.jpg}
   \caption{Fixed Block Juggling-like ARQs} 
   \label{jarq}
\end{figure}

\subsection{Fixed Block J-ARQ with Rate-less Codes}
 Rateless codes generate a virtually infinite stream from a fixed sized
 data.These packets can be transmitted with waiting for an acknowledgement. When
 sufficient number of packets are received the receiver is able to decode the
 original file. In \cite{jugglenotjuggle} the idea of combining Juggling with
 rateless codes was introduced.If the data file is encoded using rateless codes
 an infinite stream of packets are generated and there is no need for
 transmitter or the receiver to maintain the count or packet id of packets. The
 receiver only requires a minimum set of linearly independent packets. So it
 provides following benefits in communication:
 \begin{itemize}
   \item Receiver only needs to send 1 bit of information in ACK packet
   \item Retransmission does not wait for a negative- ACK
\end{itemize}
The following Figure\ref{jrateless} compares the same transmission scenario of 12
packets but this time all the packets are encoded and there are no padded packets. As the
decoding requires any set of linearly independent packets the transmission
completes before that what it does in the Juggling-like ARQ case.
\begin{figure}[h!]
\centering
   \includegraphics[scale=0.5]{./img/jarqrateless.jpg}
   \caption{J-ARQ with rateless codes} 
   \label{jrateless}
\end{figure}

\section{Paramater Calculation}

For juggling ARQ protocol to work optimally it is necessary to
have a minimum propagation delay between two nodes. Given the propagation delay
between two nodes, \cite{jugglenotjuggle} provides algorithms to choose protocol parameters 
such as block size packet length etc for ARQ and JARQ. Typical parameters used
are as follows(adapted from \cite{jugglenotjuggle}):

   
\begin{center}
\includegraphics[scale=0.5]{./img/juggling_param.png}
\end{center}
$\alpha_d$, $\beta_d$, $\alpha_c$ and $\beta_c$ are calculated
after considering the packet overheads of Link layer and Transport layer. 
Using the parameters and algorithms suggested \cite{jugglenotjuggle},
the following code snippets have been used for implementation.
\subsubsection{Calculation of $n_d$ for ARQ}
\begin{lstlisting}
 public int get_nd() {
      int nd = 0;
      double lamda = alpha_d + beta_c;
      double temp = Math.sqrt(lamda
            * (lamda - 4.0 * beta_d / (Math.log(1 - ed))))
            - lamda;
      temp = temp / (2.0 * beta_d);
      nd = (int) Math.round(temp);
      nd = modify_nd_ifneeded(nd);
      return nd;
   }

\end{lstlisting}
 
\subsubsection{Calculation of $m$ for ARQ}
\begin{lstlisting}
public int get_m() {
      int m = 0;
      double x = 2.0 * p + alpha_c;
      double lamda = alpha_d + beta_c;
      double temp1 = lamda + get_nd() * beta_d;
      double temp = Math.sqrt(4.0 * x * temp1 * ec) - x * ec;
      temp = temp / (2.0 * temp1 * ec);
      m = (int) Math.round(temp);
      return m;
   }
\end{lstlisting}
In case of J-ARQ, after every $i^{th}$ block transmission the transmitter
receives ACK for $(i-k)^{th}$ transmitted block.\\

\subsubsection{Calculation of $k$, $m$ and $n_d$  for J-ARQ}
Following Java implementation has been adopted from the optimization simulation
of \cite{jugglenotjuggle} to calculate optimal values of $k$, $m$ and $n_d$ to
get maximum throughput.

\begin{lstlisting}
   private void initJARQ() {
      double nd_shift = (alpha_d + beta_c) / beta_d;
      double nd_min = 1;
      int nd_opt = (int) Math.round(-1.0 / Math.log(1 - ed));
      nd_opt = modify_nd_ifneeded(nd_opt);
      int k_max = (int) Math.floor(2.0 * p / (alpha_d + beta_c + nd_min * beta_d + alpha_c + delta_min));
      double max_phi = 0;
      //  search over k
      for (int k = 1; k <= k_max; k++) {
         // set search range for m
         int m_max = (int) Math.floor((2.0 * p / k - alpha_c - delta_min)
 / (alpha_d + beta_c + nd_min * beta_d));
         double c = (2.0 * p / k - alpha_c - delta_min) / beta_d;
         // find nd values
         for (int m = 1; m <= m_max; m++) {
            int nd_val = (int) Math.floor(c / m - nd_shift);
            if (nd_val > nd_opt) {
               nd_val = (int) nd_opt;
            }
            if (nd_val < 1) {
               nd_val = 1;
            }
            double delta = 2.0 * p / k - alpha_c - m
                  * (alpha_d + beta_c + beta_d * nd_val);
            double t2 = 2.0 * p / k;
            double n2 = (Math.pow((1 - ec), m)) * (Math.pow((1 - ed), nd_val))
                  * m * nd_val * (gamma_c * gamma_d);
            double phi_2 = n2 / t2; 
            if (phi_2 >= max_phi) {
               max_phi = phi_2;
               best_k = k;
               best_delta = delta;
               best_m = m;
               best_nd = nd_val;
            }
         }
      }
  }
\end{lstlisting}
\subsection{Comparison with ``To Juggle or Not To
Juggle?"\cite{jugglenotjuggle}}
Most of the parameter calculations have been defined in great detail in
\cite{jugglenotjuggle} and are used as is in the implementation. However, some
additional constraints have to be considered and they are:
\subsubsection{Additional timing constraints}
Apart from data and control packet a few other timing
constraints need to be considered. Figure \ref{jarqideal} and
Figure\ref{jarqactual} illustrate a comparision between an ideal and actual
reception and transmission scenario of a packet in J-ARQ case (k=1).The
following are the additional delays which needs to be considered:

\begin{figure}[h!]
\centering
   \includegraphics[scale=0.5]{./img/jarqidle.png}
\caption{Theoritical illustration of J-ARQ }
\label{jarqideal}
\end{figure}

\begin{figure}[h!]
\centering
   \includegraphics[scale=0.5]{./img/jarqactual.png}
\caption{Illustration of J-ARQ on ARL modem }
\label{jarqactual}
\end{figure}

\begin{itemize}
  \item Rx Processing Time: Processing time required by modem after receiving
  the packet through the PHY layer.
  \item Tx Processing Time: Processing time required for creation of packet
  before transmitting through the PHY layer.
  \item Switching time from Tx to Rx: Since the modem operates in a half duplex
  mode it requires a small time duration to switch from Transmitter mode to Receiver
  mode and vice versa.
  \item Stack Processing time: All agents in modem host stack 
  communicate using FAPI messages and notifications. The overhead time
  required to perform these communications across all the layers is the stack
  processing time.
\end{itemize}
\subsubsection{Maximum packet duration constraint}
Power amplifier used in the ARL modem restricts packet duration to a certain
value(suggested by vendor). To cater to this value, a configuration
parameter is used, which restricts the packet length obtained by above
algorithms.

 \subsubsection{Utilization of OFDM Block}
Data and Control packet lengths are modified such that they utilize the OFDM
block completely. for e.g. if algorithm suggests a packet length of 13 bytes but
current OFDM block can accomodate 15 bytes, packet length is modified to 15
bytes.

\section{Challenges faced}
\begin{itemize}
\item Juggling concept depends on constraints like packet size, block size and
(calculated) delay between successive packets in a block and between successive
blocks.
These timing constraints needs to handled both at the transmitter and receiver, though 
\cite{jugglenotjuggle} provides a detailed explanation of algorithms to
calculate these values; but in the real world scenario parameters such
as packet duration need to be tuned a bit to get a pair of modems to juggle.
\item J-ARQ implementation requires a specific environment due to the
requirement of a minimum propagation delay,hence it cannot be performed in the
tank and requires field trials.
\item Predicting the scheduling time of subsequent blocks of packets requires a
through understanding and deep analysis of timing constraints.
\item Mining of large log files to understand existing state of J-ARQ
protocol.
\item All four variations of ARQ protocols require different packet headers and
ensuring that all of them work with single variable/value change requires
special handling. Also all the error scenarios need to be foreseen and dealt
with. 
\end{itemize} 

